<template>
<!--  头像组件主体-->
  <el-avatar shape="circle" :size="100"  fit="fill" alt="cat" :src="AvatarUrl" />
<!--  <img alt="Vue logo" src="../avatar/cat.png">-->
</template>

<script>
import axios from "axios";

export default {
  name: "AvatarComponent",
  /**
   * userName：父组件传来的username信息，用于查询数据库中该用户的头像信息
   */
  props: ['userName'],
  data() {
    return {
      /**
       * AvatarUrl:头像地址
       */

      AvatarUrl: '',
      // url:  require('@/assets/'+this.AvatarUrl)
    }
  },
  //watch函数，监控userName数据的变化，每次变化都请求后端查询头像，做到实时渲染
  watch:{
    /**
     *
     * @param newVal:变化后的值
     * @param oldVal:变化前的值
     */

    userName(newVal,oldVal){
      const _this=this
      console.log(newVal)
      axios({
        method: 'post',
        url: 'http://localhost:8081/showUserByAdmin',
        params: {
          userName: newVal
        }
      })
          .then(function (response) {
            console.log(response.data);

            if(response.data.at(0)!=null){
              //将数据库拿到的url传给前端
              _this.AvatarUrl=response.data.at(0).avatarUrl
            }else {
              //释放
              _this.AvatarUrl=''
            }
          })
          .catch(function (error) {
            console.log(error);

          });

    },
  },
  //页面刚加载时，头像渲染
  created() {
    const _this = this
    /**
     * API
     * http://localhost:8081/showUserByAdmin
     * input:userName 账户
     * output:user(Object) 用户实体
     */
    axios({
      method: 'post',
      url: 'http://localhost:8081/showUserByAdmin',
      params: {
        userName: this.userName
      }
    })
        .then(function (response) {
          console.log(response.data);
          if(response.data.at(0)!=null){
            //将数据库拿到的url传给前端
            _this.AvatarUrl=response.data.at(0).avatarUrl

          }else {
            _this.AvatarUrl=''
          }
        })
        .catch(function (error) {
          console.log(error);

        });
  },
}
</script>
<style scoped>

</style>